#!/usr/bin/env python
#-*-encoding:utf-8-*-
'''
Created on 2015年7月30日

@author: chenyongbing
'''
import sys,os,re,commands
#current_dir = os.path.dirname(__file__)
current_dir = os.path.split(os.path.realpath(__file__))[0]
import openpyxl
import logging
logging.basicConfig(level = logging.DEBUG)
sys.path.append(os.path.join(current_dir,'../'))
from base.retail_datas import myRetailDatas
#from base.zhimind_datas import myZhimindDatas
from base.localConfig import baseLocalConfig
#zhimind_host = baseLocalConfig.mysqlConfig['zhimind']['host']
zhimind_host = 'zm12'
zhimind_user = baseLocalConfig.mysqlConfig['zhimind']['user']
zhimind_passwd = baseLocalConfig.mysqlConfig['zhimind']['passwd']
zhimind_db = baseLocalConfig.mysqlConfig['zhimind']['db']
class analyzeDemand():
    
    def __init__(self,host='localhost',user='root',passwd='',db='zhimind',testing=False):
        self.mysql_host = host
        self.mysql_user = user
        self.mysql_passwd = passwd
        self.mysql_db = db
        self.testing = testing
    
    
    def analyze_temp_1(self,import_file=''):
        wb = openpyxl.load_workbook(import_file)
        #ws = wb.get_sheet(1)
        ws = wb.get_sheet_by_name(wb.get_sheet_names()[0])
#  需求分析       
#         *需求提出人姓名    
#         *公司名称    
#         *所属行业    
#         *报告申请人邮箱    
#         *分析报告规模（客群数量）    
#         需求提出日期    
#         需求单编号    

#         demand_people = ws.cell(row=2,column=3).value
#         demand_comp_name = ws.cell(row=3,column=3).value
#         demand_comp_type = ws.cell(row=4,column=3).value
#         demand_people_email = ws.cell(row=5,column=3).value
#         demand_mac_count = ws.cell(row=6,column=3).value
#         demand_date = ws.cell(row=7,column=3).value
#         demand_num = ws.cell(row=8,column=3).value
        

        
        for row in range(2,9):
            name  = ws.cell(row=row,column=1).value
            value = ws.cell(row=row,column=3).value
            logging.debug('%s:%s'%(name,value))
            if type(name).__name__=='unicode':
                name = name.encode("utf-8")
            if type(value).__name__=='unicode':
                value = value.encode("utf-8")
                
            if re.search('^\*',name) and(value==None or value=='' or  re.search('此处由芝麻科技填写',value)):
                logging.error('%s Is Required.'%name)
                sys.exit()
            if row == 3:
                demand_comp_name = value
            if row == 4:
                demand_comp_type = value
            if row == 8:
                demand_num = value
        demand_comp_id = myRetailDatas.get_comp_id( comp_name = demand_comp_name)

        if demand_comp_id == None:
            logging.error('Company Name %s Not Exists In Retail DataBase.'%demand_comp_name)
            sys.exit(1)            
        
# mac 圈定
        for row in range(11,18):
            name = ws.cell(row=row,column=2).value
            value = ws.cell(row=row,column=3).value
            logging.debug('%s:%s'%(name,value))
            if type(name).__name__=='unicode':
                name = name.encode("utf-8")

            if type(value).__name__=='unicode':
                value = value.encode("utf-8")
            if re.search('^\*',name) and(value==None or value=='' or  re.search('此处由芝麻科技填写',value)):
                logging.error('%s Is Required.'%name)
                sys.exit()
            
            
            
#圈定分析标签
        tags = []
        for row in range(20,80):
            name = ws.cell(row=row,column=2).value
            value = ws.cell(row=row,column=3).value
            logging.debug('%s:%s'%(name,value))
            if type(name).__name__=='unicode':
                name = name.encode("utf-8")

            if type(value).__name__=='unicode':
                value = value.encode("utf-8")
            if value == True:
                tags.append(name)

    
    
        
        query = "insert into analysis (data_name  , brand , account_no,tags ,data_size,line_cnt) VALUES ('%s','%s','%s','%s',0,0)"%(demand_num,demand_comp_type,demand_comp_id,','.join(tags))
        
        logging.error( query)
        cmd = '/data/mysql/bin/mysql -h%s -u%s -p%s %s -e "%s"'%(self.mysql_host,self.mysql_user,self.mysql_passwd,self.mysql_db,query)
        logging.debug(cmd)
        if self.testing==False:
            out = commands.getstatusoutput(cmd)
            logging.debug(out)

            
        
if __name__=='__main__':
    import argparse
    parser = argparse.ArgumentParser(description='args')
    parser.add_argument('--import_file',metavar="import file",required=False)
    parser.add_argument('--rule',metavar="文件后缀",default='temp_1')
    parser.add_argument('--testing',action='store_true',help='testing')

  
    args = parser.parse_args()
    import_file = args.import_file
    testing = args.testing
    
    myAnalyzeDemand = analyzeDemand(host=zhimind_host,user=zhimind_user,passwd=zhimind_passwd,db=zhimind_db,testing=testing)
    myAnalyzeDemand.analyze_temp_1(import_file)
    